package com.wj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wj.dao.AdminMapper;
import com.wj.dao.AdminRoleMapper;
import com.wj.dao.RoleMapper;
import com.wj.pojo.Admin;
import com.wj.pojo.AdminRole;
import com.wj.pojo.RespBean;
import com.wj.pojo.Role;
import com.wj.service.IAdminService;
import com.wj.utils.AdminUtil;
import com.wj.utils.FastDFSUtil;
import com.wj.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wj
 * @since 2022-03-05
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtUtil jwtUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private AdminRoleMapper adminRoleMapper;

    /**
     * 根据用户id获取权限列表
     *
     * @param id
     * @return
     */
    @Override
    public List<Role> getRoles(Integer id) {
        return roleMapper.getRoles(id);
    }

    /**
     * 获取所有操作员
     *
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtil.getCurrentAdmin().getId(), keywords);
    }

    /**
     * 更新操作员角色
     *
     * @param adminId
     * @param rids
     * @return
     */
    @Transactional
    @Override
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));
        if (adminRoleMapper.addAdminRole(adminId, rids) > 0) {
            return RespBean.success("更改成功");
        }
        return RespBean.error("更改失败");
    }

    /**
     * 更新密码
     *
     * @param adminId
     * @param oldPass
     * @param pass
     * @return
     */
    @Override
    public RespBean updatePassword(Integer adminId, String oldPass, String pass) {
        Admin admin = adminMapper.selectById(adminId);
        if (passwordEncoder.matches(oldPass, admin.getPassword())) {
            admin.setPassword(passwordEncoder.encode(pass));
            adminMapper.updateById(admin);
            return RespBean.success("密码修改成功");
        }
        return RespBean.error("旧密码错误");
    }

    /**
     * 更新用户头像
     *
     * @param file
     * @param id
     * @return
     */
    @Override
    public RespBean updateUserFace(MultipartFile file, Integer id) {
        String remoteFileName = FastDFSUtil.uploadFile(file);
        if (StringUtils.hasText(remoteFileName)) {
            Admin currentAdmin = AdminUtil.getCurrentAdmin();
            currentAdmin.setUserFace(FastDFSUtil.getTrackerUrl()+remoteFileName);
            if (adminMapper.updateById(currentAdmin) > 0) {
                return RespBean.success("头像更换成功");
            }
        }
        return RespBean.error("头像更换失败");
    }

    /**
     * 登录之后返回Token
     *
     * @param userName
     * @param passWord
     * @return
     */
    @Override
    public RespBean login(String userName, String passWord, String code, HttpServletRequest request) {
        //检查验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (!StringUtils.hasText(captcha) || !captcha.equals(code)) {
            return RespBean.error("验证码错误，请重新输入！");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        if (userDetails == null || !passwordEncoder.matches(passWord, userDetails.getPassword())) {
            return RespBean.error("用户名或密码错误！");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号已被禁用，请联系客服！");
        }

        UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(userToken);

        //生成Token
        HashMap<String, Object> respMap = new HashMap<>();
        String token = jwtUtil.generateToken(userDetails);
        respMap.put("token", token);
        respMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功", respMap);
    }

    /**
     * 根据用户名查用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public Admin getAdminByUserName(String userName) {
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", userName);
        return adminMapper.selectOne(qw);
    }
}
